package com.orkasgb.controller;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.orkasgb.common.CommonResult;
import com.orkasgb.entity.OrkasgbUserEntity;
import com.orkasgb.service.IOrkasgbUserService;
import jakarta.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 登录测试
 */
@RestController
@RequestMapping("/login/")
public class LoginController {

    @Resource
    private IOrkasgbUserService orkasgbUserService;

    @RequestMapping("doLogin")
    public CommonResult<OrkasgbUserEntity> doLogin(@RequestParam("name") String name, @RequestParam("password") String password) {
        OrkasgbUserEntity orkasgbUser = new OrkasgbUserEntity();
        orkasgbUser.setUserAccount(name);
        List<OrkasgbUserEntity> orkasgbUserList = orkasgbUserService.getOrkasgbUserList(orkasgbUser);
        if (CollectionUtils.isEmpty(orkasgbUserList) || orkasgbUserList.size() > 1) {
            return CommonResult.ofFailure(HttpStatus.BAD_REQUEST.value(), "用户名或密码错误", null);
        }

        orkasgbUser = orkasgbUserList.get(0);
        if (!orkasgbUser.getPassword().equals(password)) {
            return CommonResult.ofFailure(HttpStatus.BAD_REQUEST.value(), "用户名或密码错误", null);
        }

        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
        SaLoginModel saLoginModel = SaLoginModel.create();
        saLoginModel.setDevice("pc");
        saLoginModel.setTimeout(3600 * 24 * 7);
        StpUtil.login(orkasgbUser.getId() + "_" + orkasgbUser.getUserAccount(), saLoginModel);
        return CommonResult.ofSuccess(orkasgbUser);
    }

    @RequestMapping("isLogin")
    public SaResult isLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }

    @RequestMapping("tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    @RequestMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }

}
